<template>
  <div>
    <a-modal v-model="visible" title="修改收货地址" :centered="true" width="1152px" destroyOnClose @ok="handleAddress" @cancel="closeAddress">
      <a-button style="margin-bottom: 18px" type="primary" @click="determine('')"><a-icon type="plus" /> 新增</a-button>
      <a-table :columns="columns" :dataSource="addressList" rowKey="id" :rowSelection="{ selectedRowKeys: selectedRowKeys, onSelect: onSelect, onChange: onSelectChange, type: 'radio' }">
        <template slot="contactName" slot-scope="text, record">
          <span class="default" v-if="record.logDefault == 1">【默认】</span>
          <span>{{ record.contactName }}</span>
        </template>
        <template slot="esContent" slot-scope="text, record">
          <span>{{ record.province }}{{ record.city }}{{ record.district }}</span>
        </template>
        <template slot="action" slot-scope="text, record">
          <a @click="determine(record)" class="determine">编辑</a>
          <a @click="delAddress(record.id)" class="determine">删除</a>
          <a @click="defaultClick(record)" class="determine" v-if="record.logDefault != 1">设为默认</a>
        </template>
        <template slot="dealerBrands" slot-scope="text, record">
          {{ record.dealerBrands | dealerBrands }}
        </template>
      </a-table>
    </a-modal>
    <!-- 编辑 新增地址 -->
    <a-modal :visible="visibleEdit" :title="title" :centered="true" @ok="handleEdit" @cancel="closeEdit">
      <a-form>
        <a-form-item label="姓名" required>
          <a-input v-model="editAdds.contactName" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="联系电话" required>
          <a-input v-model="editAdds.contactPhone" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="省市区" required>
          <a-cascader :options="pcaOptions" :value="pcaDefault" placeholder="请选择省市区" @change="pcaChange" />
        </a-form-item>
        <a-form-item label="详细地址" required>
          <a-input v-model="editAdds.address" placeholder="请输入详细地址" />
        </a-form-item>
        <a-form-item>
          <a-checkbox @change="checkDefault" :checked="logDefault"> 设为默认地址 </a-checkbox>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
import { selectLogistics, getAreaData, saveLogistic } from '@/api/box/workbench'
import { delLogisticsById } from '@/api/box/api'
const columns = [
  {
    title: '姓名',
    dataIndex: 'contactName',
    scopedSlots: { customRender: 'contactName' }
  },
  {
    title: '联系电话',
    dataIndex: 'contactPhone'
  },
  {
    title: '省市区',
    dataIndex: '',
    scopedSlots: { customRender: 'esContent' }
  },
  {
    title: '详细地址',
    dataIndex: 'address'
  },
  {
    title: '经销品牌',
    dataIndex: 'dealerBrands',
    scopedSlots: { customRender: 'dealerBrands' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  props: {
    userInfo: {
      type: Object,
      default: null
    },
    initData: {
      type: Object,
      default: null
    }
  },
  components: {},
  filters: {
    dealerBrands(v) {
      if (v.length > 0) {
        return v.join('、')
      } else {
        return '-'
      }
    }
  },
  data() {
    return {
      columns,
      visible: false,
      logDefault: false,
      dealerBrand: {},
      addressList: [],
      addsValue: '',
      currAddsId: '',
      visibleEdit: false,
      editAdds: {
        contactName: null,
        contactPhone: null,
        address: null
      },
      pcaOptions: [],
      pcaDefault: [],
      selectedRowKeys: [],
      title: '',
      defLogistic: {},
      dealerBrandList: [],
      unionId: ''
    }
  },
  watch: {
    initData: {
      handler(value, oldvalue) {
        if (value) {
          this.visible = value.visibleAddList
          this.unionId = value.unionId
          this.defLogistic = value.defLogistic
          this.fetchAddressList()
        }
      },
      deep: true
    }
  },
  created() {
    this.editAddress()
  },
  methods: {
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    onSelect(onSelectRow) {
      this.dealerBrandList = onSelectRow.dealerBrands
    },
    // 新增 / 编辑地址
    determine(record) {
      this.title = record.id ? '修改收货地址' : '新增收货地址'
      if (record.id) {
        this.logDefault = record.logDefault == 1 ? true : false
        this.pcaDefault = [record.province, record.city, record.district]
        this.editAdds = JSON.parse(JSON.stringify(record))
        this.editAddress()
      }
      this.visibleEdit = true
    },
    delAddress(id) {
      delLogisticsById(id).then(res => {
        if (res.code == 0) {
          this.$message.success('删除成功！')
          this.fetchAddressList()
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    // 设置是否默认
    defaultClick(item) {
      this.logDefault = true
      const data = {
        requestData: {
          id: item.id,
          logDefault: this.logDefault ? '1' : '0'
        },
        user_id: this.userInfo.id
      }
      saveLogistic(data)
        .then(res => {
          if (res.code === 0) {
            this.$message.success('设置成功')
            this.fetchAddressList()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log('编辑地址确定：' + err)
        })
    },
    checkProps() {},
    // 查看顾客地址列表
    fetchAddressList() {
      selectLogistics(this.unionId).then(res => {
        if (res.code === 0) {
          this.addressList = res.data
          if (this.defLogistic) {
            this.selectedRowKeys = [this.defLogistic.id]
            this.addressList.forEach(item => {
              if (item.id == this.defLogistic.id) {
                this.$nextTick(() => {
                  this.$emit('dealerBrand', item.dealerBrands)
                })
              }
            })
          }
        } else {
          this.$message.error(res.data)
        }
      })
    },
    // 选择地址
    addsChange(e) {
      this.currAddsId = e.target.value
    },
    // 确定选中地址
    handleAddress() {
      const result = this.addressList.filter(item => item.id === this.selectedRowKeys.toString())
      console.log(result[0], 'result[0]')
      this.visible = false
      this.$emit('closeAddress', false)
      this.$emit('newAddress', result[0])
      this.$emit('dealerBrand', this.dealerBrandList)
    },
    // 取消关闭选择地址
    closeAddress() {
      const result = this.addressList.filter(item => item.id === this.selectedRowKeys.toString())
      this.$emit('newAddress', result[0])
      this.visible = false
      this.$emit('closeAddress', false)
    },
    // 省市区数据
    getAreaData() {
      return getAreaData()
        .then(res => {
          return res
        })
        .catch(err => {
          console.log('省市区数据:' + err)
        })
    },
    // 编辑地址
    async editAddress() {
      if (this.pcaOptions.length === 0) {
        const result = await this.getAreaData()
        if (result.code === 0) {
          this.pcaOptions = result.data
        } else {
          this.$message.error(result.msg)
        }
      }
    },
    // 设置默认地址
    checkDefault(e) {
      this.logDefault = e.target.checked
    },
    // 编辑地址确定
    handleEdit() {
      if (this.editAdds.contactName && this.editAdds.contactPhone && this.editAdds.address && this.pcaDefault.length > 0) {
        const data = {
          requestData: {
            address: this.editAdds.address,
            city: this.pcaDefault[1],
            contactName: this.editAdds.contactName,
            contactPhone: this.editAdds.contactPhone,
            district: this.pcaDefault[2],
            logDefault: this.logDefault ? '1' : '0',
            province: this.pcaDefault[0]
          },
          user_id: this.userInfo.id
        }
        if (this.editAdds.id) {
          data.requestData.id = this.editAdds.id
        } else if (this.unionId !== '') {
          data.requestData.unionId = this.unionId
        }
        saveLogistic(data)
          .then(res => {
            if (res.code === 0) {
              this.$message.success('修改成功！')
              this.closeEdit()
              this.fetchAddressList()
            } else {
              this.$message.error(res.msg)
            }
          })
          .catch(err => {
            console.log('编辑地址确定：' + err)
          })
      } else {
        this.$message.error('请填写全部地址信息！')
      }
    },
    // 关闭地址编辑
    closeEdit() {
      this.visibleEdit = false
      this.editAdds = {}
      this.pcaDefault = []
    },
    // 变更省市区
    pcaChange(value) {
      console.log(value)
      this.pcaDefault = value
    }
  }
}
</script>
<style lang="less" scoped>
.determine {
  margin-right: 12px;
}
.default {
  color: #1890ff;
  width: 60px;
}
</style>